package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.constant.ProductConst;
import com.atguigu.gmall.list.feign.GoodsFeign;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 分类与属性管理实现类
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ManageServiceImpl implements ManageService {
    @Resource
    private BaseCategory1Mapper baseCategory1Mapper;
    @Resource
    private BaseCategory2Mapper baseCategory2Mapper;
    @Resource
    private BaseCategory3Mapper baseCategory3Mapper;
    @Resource
    private BaseAttrInfoMapper baseAttrInfoMapper;
    @Resource
    private BaseAttrValueMapper baseAttrValueMapper;
    /**
     * 获取一级分类全部数据
     *
     * @return
     */
    @Override
    public List<BaseCategory1> getBaseCategory1() {
        return baseCategory1Mapper.selectList(null);
    }

    /**
     * 根据一级分类Id获取二级分类数据
     *
     * @param category1Id
     * @return
     */
    @Override
    public List<BaseCategory2> getBaseCategory2(Long category1Id) {
        return baseCategory2Mapper.
                selectList(new LambdaQueryWrapper<BaseCategory2>().
                        eq(BaseCategory2::getCategory1Id,category1Id));
    }

    /**
     * 根据二级分类id获取三级分类
     *
     * @param category2Id
     * @return
     */
    @Override
    public List<BaseCategory3> getBaseCategory3(Long category2Id) {
        return baseCategory3Mapper.
                selectList(new LambdaQueryWrapper<BaseCategory3>().
                        eq(BaseCategory3::getCategory2Id,category2Id));
    }

    /**
     * 获取属性列表
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<BaseAttrInfo> getAttrInfoList(Long categoryId) {
        return baseAttrInfoMapper.getAttrInfoList(categoryId);
    }

    /**
     * 添加/修改平台属性
     *
     * @param baseAttrInfo
     */
    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //判断平台属性名的合法性
        if (baseAttrInfo ==null || StringUtils.isEmpty(baseAttrInfo.getAttrName())){
            throw new RuntimeException("参数异常");
        }
        //根据是否带有ID判断是新增还是修改操作
        if (baseAttrInfo.getId() != null){
            //修改平台熟悉名
            int update = baseAttrInfoMapper.updateById(baseAttrInfo);
            if (update < 0){
                throw new RuntimeException("修改平台属性名失败");
            }
            //将旧属性名对应的属性值数据删除
            int delete = baseAttrValueMapper.
                    delete(new LambdaQueryWrapper<BaseAttrValue>().
                            eq(BaseAttrValue::getAttrId, baseAttrInfo.getId()));
            if (delete <= 0){
                throw new RuntimeException("删除平台属性值失败！！！");
            }
          }else {
            //添加平台属性名
            int insert = baseAttrInfoMapper.insert(baseAttrInfo);
            if (insert <= 0){
                throw new RuntimeException("添加平台属性名失败！！");
            }
        }
        //获取新增的平台熟悉的id
        Long attrInfoId = baseAttrInfo.getId();
        //根据平台属性Id获取平台属性的值
        List<BaseAttrValue> baseAttrValueList = baseAttrInfo.getAttrValueList();
        //判断平台属性值的合法性
        baseAttrValueList.stream().forEach(baseAttrValue -> {
            if (!StringUtils.isEmpty(baseAttrValue.getValueName())){
                //添加平台属性值
                baseAttrValue.setAttrId(attrInfoId);
                int insert1 = baseAttrValueMapper.insert(baseAttrValue);
                if (insert1 <= 0){
                    throw new RuntimeException("添加平台属性值失败！！");
                }
            }
        });

    }

    /**
     * 删除平台属性值
     *
     * @param id
     */
    @Override
    public void deleteAttrInfo(Long id) {
        if (id == null){
            return;
        }
        int delete = baseAttrInfoMapper.deleteById(id);
        if (delete <= 0){
            throw new RuntimeException("删除平台属性名失败！！");
        }
        int delete1 = baseAttrValueMapper.
                delete(new LambdaQueryWrapper<BaseAttrValue>().
                        eq(BaseAttrValue::getAttrId, id));
        if (delete1 <=0 ){
            throw new RuntimeException("删除平台属性值失败");
        }
    }

    @Resource
  private   BaseTrademarkMapper baseTrademarkMapper;
    /**
     * 获取品牌
     *
     * @return
     */
    @Override
    public List<BaseTrademark> getTrademarkList() {
        return baseTrademarkMapper.selectList(null);
    }
    /**
     * 分页查询品牌
     *  @param page
     * @param size
     * @return
     */
    @Override
    public IPage<BaseTrademark> getBaseTrademarkList(Integer page, Integer size) {
        return baseTrademarkMapper.selectPage(new Page<>(page, size), null);
    }

    /**
     * 添加品牌
     *
     * @param baseTrademark
     */
    @Override
    public void saveBaseTrademark(BaseTrademark baseTrademark) {
        if (baseTrademark == null || StringUtils.isEmpty(baseTrademark.getTmName())){
            throw new RuntimeException("参数异常！！！");
        }
        int insert = baseTrademarkMapper.insert(baseTrademark);
        if (insert <=0 ){
            throw new RuntimeException("添加品牌失败！！！");
        }
    }


    /**
     * 修改品牌
     *
     * @param baseTrademark
     */
    @Override
    public void updateBaseTrademark(BaseTrademark baseTrademark) {
        if (baseTrademark == null || StringUtils.isEmpty(baseTrademark.getTmName())){
            throw new RuntimeException("参数异常！！！");
        }
        int update = baseTrademarkMapper.updateById(baseTrademark);
        if (update < 0){
            throw new RuntimeException("修改品牌失败！！！");
        }
    }

    /**
     * 根据Id查询品牌信息
     *
     * @param id
     * @return
     */
    @Override
    public BaseTrademark getBaseTrademark(Long id) {
        return baseTrademarkMapper.selectById(id);
    }

    /**
     * 删除品牌
     *
     * @param id
     */
    @Override
    public void removeBaseTrademark(Long id) {
        if (id == null){
            return;
        }
        int i = baseTrademarkMapper.deleteById(id);
        if (i <= 0){
            throw new RuntimeException("删除品牌失败！！！");
        }
    }

    @Resource
    private BaseSaleAttrMapper baseSaleAttrMapper;
    /**
     * 获取销售属性值
     *
     * @return
     */
    @Override
    public List<BaseSaleAttr> getBaseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }

    @Resource
    private SpuInfoMapper spuInfoMapper;
    @Resource
    private SpuImageMapper spuImageMapper;
    @Resource
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;
    @Resource
    private SpuSaleAttrMapper spuSaleAttrMapper;
    /**
     * 新增/修改 supInfo
     *
     * @param spuInfo
     */
    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        // 参数检验
        if (spuInfo == null){
            throw new RuntimeException("参数异常！！");
        }
        //判断新增还是修改
        if (spuInfo.getId() != null){
            //修改
            int update = spuInfoMapper.updateById(spuInfo);
            if (update < 0 ){
                throw new RuntimeException("修改SpuInfo 失败！！！");
            }
            //删除图片
            int deleteSpuImage = spuImageMapper.delete
                    (new LambdaQueryWrapper<SpuImage>().
                            eq(SpuImage::getSpuId, spuInfo.getId()));

            //删除销售属性名
            int deleteSpuSaleAttr = spuSaleAttrMapper.delete
                    (new LambdaQueryWrapper<SpuSaleAttr>().
                            eq(SpuSaleAttr::getSpuId, spuInfo.getId()));

            //删除销售属性值
            int deleteSpuSaleAttrValue = spuSaleAttrValueMapper.
                    delete(new LambdaQueryWrapper<SpuSaleAttrValue>().
                            eq(SpuSaleAttrValue::getSpuId, spuInfo.getId()));
            //判断删除结果
            if (deleteSpuImage <= 0||deleteSpuSaleAttr <= 0 || deleteSpuSaleAttrValue <= 0){
                throw new RuntimeException("修改不成功，删除原数据失败！！");
            }
        }else {
            //新增SpuInfo
            int insertSpuInfo = spuInfoMapper.insert(spuInfo);
            if (insertSpuInfo <= 0 ){
               throw new RuntimeException("新增spuInfo失败！！");
            }
        }

        //获取spuInfo id
        Long spuInfoId = spuInfo.getId();
        //新增图片
        saveSpuImage(spuInfoId,spuInfo.getSpuImageList());
        //新增商品属性名
        saveSpuSaleAttr(spuInfoId,spuInfo.getSpuSaleAttrList());


    }

    /**
     * 新增销售属性名
     * @param spuInfoId
     * @param spuSaleAttrList
     */
    private void saveSpuSaleAttr(Long spuInfoId, List<SpuSaleAttr> spuSaleAttrList) {
        //遍历spuSaleAttrList
        spuSaleAttrList.stream().forEach(spuSaleAttr -> {
            //设置spuId
            spuSaleAttr.setSpuId(spuInfoId);
            //新增
            int insertSpuSaleAttr = spuSaleAttrMapper.insert(spuSaleAttr);
            if (insertSpuSaleAttr < 0){
                throw new RuntimeException("新增销售属性名失败");
            }
            //新增销售属性值
            saveSpuSaleAttrValue(spuInfoId,
                    spuSaleAttr.getSaleAttrName(),
                    spuSaleAttr.getSpuSaleAttrValueList());
        });
    }

    /**
     * 分页查询spuInfo
     *  @param page
     * @param size
     * @param category3Id
     * @return
     */
    @Override
    public IPage<SpuInfo> getSpuInfoList(Integer page, Integer size, Long category3Id) {
        return spuInfoMapper.selectPage(new Page<>(page, size),
                new LambdaQueryWrapper<SpuInfo>().
                        eq(SpuInfo::getCategory3Id, category3Id));
    }


    @Resource
    private SkuInfoMapper skuInfoMapper;
    /**
     * 分页查询SkuInfo
     *  @param page
     * @param size
     * @return
     */
    @Override
    public IPage<SkuInfo> getSkuInfoList(Integer page, Integer size) {
        return skuInfoMapper.selectPage(new Page<>(page, size), null);
    }

    /**
     * 根据SpuId 获取销售属性图片
     *
     * @param spuId
     * @return
     */
    @Override
    public List<SpuImage> getSpuImageList(Long spuId) {
        return spuImageMapper.
                selectList(new LambdaQueryWrapper<SpuImage>().
                        eq(SpuImage::getSpuId,spuId));
    }

    /**
     * 根据SpuId 获取销售属性的名和值
     *
     * @param spuId
     * @return
     */
    @Override
    public List<SpuSaleAttr> getSpuSaleAttrList(long spuId) {
        return spuSaleAttrMapper.getSpuSaleAttrList(spuId);
    }

    @Autowired
    private GoodsFeign goodsFeign;

    @Autowired
    RabbitTemplate rabbitTemplate;
    /**
     * 上下架商品
     *
     * @param skuId
     * @param status
     */
    @Override
    public void upOrDown(Long skuId, short status) {
        if (skuId == null){
            return;
        }
        //回显数据
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        //修改销售状态
        skuInfo.setIsSale(status);
        //修改数据表
        int updateById = skuInfoMapper.updateById(skuInfo);
        if (updateById <= 0){
            throw new RuntimeException("修改商品销售状态失败");
        }
        if (status == ProductConst.SKU_CANCLE_SALE){

            //使用rabbitMq实现异步操作 --todo
            rabbitTemplate.convertAndSend("product_exchange","sku_down",skuId+"");
            //goodsFeign.removeGoods(skuId);
        }else {
            rabbitTemplate.convertAndSend("product_exchange","sku_upper",skuId+"");
            //goodsFeign.addGoods(skuId);
        }

    }

    @Resource
    private SkuImageMapper skuImageMapper;
    @Resource
    private SkuAttrValueMapper skuAttrValueMapper;
    @Resource
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;
    /**
     * 新增/修改sku 表数据
     *
     * @param skuInfo
     */
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
        //检验参数
        if (skuInfo ==null){
            throw new RuntimeException("参数异常！！！");
        }
        //判断是新增还是修改
        if (skuInfo.getId()!=null){
            //修改
            int update = skuInfoMapper.updateById(skuInfo);
            if (update <= 0){
                throw new RuntimeException("修改skuInfo 失败！！！");
            }
            //删除 图片
            int deleteImage =
                    skuImageMapper.delete(new LambdaQueryWrapper<SkuImage>()
                            .eq(SkuImage::getSkuId, skuInfo.getId()));
            // 删除平台属性
            int deleteAttr = skuAttrValueMapper.
                    delete(new LambdaQueryWrapper<SkuAttrValue>()
                            .eq(SkuAttrValue::getSkuId, skuInfo.getId()));
            // 删除 销售属性

            int deleteSaleAttr = skuSaleAttrValueMapper
                    .delete(new LambdaQueryWrapper<SkuSaleAttrValue>()
                            .eq(SkuSaleAttrValue::getSkuId, skuInfo.getId()));
            if (deleteImage < 0 || deleteAttr < 0 || deleteSaleAttr < 0 ){
                throw new RuntimeException("删除不成功，修改SkuInfo失败");
            }

        }else {
            //新增
            int insert = skuInfoMapper.insert(skuInfo);
            if (insert < 0){
                throw new RuntimeException("新增skuInfo失败！！");
            }

        }
        //获取skuId
        Long skuInfoId = skuInfo.getId();
        //新增图片
        saveSkuImage(skuInfoId,skuInfo.getSkuImageList());
        //新增平台属性值
        saveSkuAttrValue(skuInfoId,skuInfo.getSkuAttrValueList());
        //新增销售属性
        saveSkuSaleAttrVale(skuInfoId,skuInfo.getSkuSaleAttrValueList(),skuInfo.getSpuId());
    }

    /**
     * 新增sku销售属性
     * @param skuInfoId
     * @param skuSaleAttrValueList
     * @param spuId
     */
    private void saveSkuSaleAttrVale(Long skuInfoId,
                                     List<SkuSaleAttrValue> skuSaleAttrValueList,
                                     Long spuId) {
        //遍历
        skuSaleAttrValueList.stream().forEach(skuSaleAttrValue -> {
            //设置skuId
            skuSaleAttrValue.setSkuId(skuInfoId);
            //设置spuID
            skuSaleAttrValue.setSpuId(spuId);
            //新增
            int insert = skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            if (insert < 0){
                throw new RuntimeException("新增sku销售属性失败！！！");
            }
        });
    }

    /**
     * 新增平台属性
     * @param skuInfoId
     * @param skuAttrValueList
     */
    private void saveSkuAttrValue(Long skuInfoId, List<SkuAttrValue> skuAttrValueList) {
        //遍历
        skuAttrValueList.stream().forEach(skuAttrValue -> {
            //设置SkuID
            skuAttrValue.setSkuId(skuInfoId);
            //新增
            int insert = skuAttrValueMapper.insert(skuAttrValue);
            if (insert < 0){
                throw new RuntimeException("新增sku平台属性值失败");
            }
        });
    }

    /**
     * 新增sku图片
     * @param skuInfoId
     * @param skuImageList
     */
    private void saveSkuImage(Long skuInfoId, List<SkuImage> skuImageList) {
        //遍历每一张图片
        skuImageList.stream().forEach(skuImage -> {
            //设置skuID
            skuImage.setSkuId(skuInfoId);
            //新增
            int insert = skuImageMapper.insert(skuImage);
            if (insert < 0){
                throw new RuntimeException("新增sku图片失败！！！");
            }
        });

    }

    /**
     * 新增销售属性值
     * @param saleAttrName
     * @param spuInfoId
     * @param saleAttrName
     * @param spuSaleAttrValueList
     */
    private void saveSpuSaleAttrValue(Long spuInfoId, String saleAttrName, List<SpuSaleAttrValue> spuSaleAttrValueList) {
        //遍历销售属性值
        spuSaleAttrValueList.stream().forEach(spuSaleAttrValue -> {
            //设置spuId
            spuSaleAttrValue.setSpuId(spuInfoId);
            //设置销售属性名
            spuSaleAttrValue.setSaleAttrName(saleAttrName);
            int insertSpuSaleAttrValue = spuSaleAttrValueMapper.insert(spuSaleAttrValue);
            if (insertSpuSaleAttrValue < 0){
                throw new RuntimeException("新增商品属性值失败！！！");
            }
        });
    }

    /**
     *新增图片
     * @param spuInfoId
     * @param spuImageList
     */
    private void saveSpuImage(Long spuInfoId, List<SpuImage> spuImageList) {
        //遍历SpuImageList
        spuImageList.stream().forEach(spuImage -> {
            //设置spuId
            spuImage.setSpuId(spuInfoId);
            //新增
            int insertSpuImage = spuImageMapper.insert(spuImage);
            if (insertSpuImage < 0){
                throw new RuntimeException("新增SpuImage 图片失败！！！");
            }
        });
    }


}
